package com.starsky.project.service.impl;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.starsky.common.util.DateUtils;
import com.starsky.common.util.easypoi.WordUtils;
import com.starsky.project.mapper.BookInfoMapper;
import com.starsky.project.service.WordService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class WordServiceImpl implements WordService {

    @Autowired
    private BookInfoMapper bookInfoMapper;


    private static List<Map<String, Object>> getData() {
        List<Map<String, Object>> dataList = new ArrayList();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("year", "2023年");
        dataMap.put("peopleCount", "2.74亿人次");
        dataMap.put("addOrReduce", "+70.83%");
        dataMap.put("previousYear", "119.09%");
        dataList.add(dataMap);

        Map<String, Object> dataMap2 = new HashMap<>();
        dataMap2.put("year", "2022年");
        dataMap2.put("peopleCount", "1.6亿人次");
        dataMap2.put("addOrReduce", "-30.2%");
        dataMap2.put("previousYear", "66.8%");
        dataList.add(dataMap2);
        return dataList;
    }

    /**
     * 导出带表格的word
     */
    public void exportTableWord(HttpServletResponse response) {

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("title", "2024年五一出行统计");
            map.put("projectBackground", "故宫博物院：位于北京，是世界三大宫殿之一，也是中国最大的古代文化艺术博物馆。故宫保存了大量的清代皇家建筑、文物藏品，如太和殿、中和殿、保和殿、养心殿、乾清宫等，以及丰富的古书画、瓷器、铜器、玉器等艺术品.\\\r\\\n" +
                    "万里长城：作为中国古代军事防御工程，长城是世界文化遗产，被誉为世界七大奇迹之一。其中最著名的是北京八达岭长城，以其壮观的景观、丰富的历史文化内涵和完善的旅游设施吸引着全球游客。");
            map.put("touristAttraction", "桂林山水：“桂林山水甲天下”，以漓江为代表的桂林山水是中国山水的典型代表，以其独特的喀斯特地貌和秀美的自然风光闻名于世。漓江风景名胜区内有象鼻山、冠岩、黄布倒影、仙人推磨等景点");

            // 模版文件：starsky-excel/src/main/resource/template/wordmodel.xlsx
            String templateUrl = "G:\\wordmodel.docx";
            XWPFDocument document = WordExportUtil.exportWord07(templateUrl, map);
            List<XWPFParagraph> paragraphs = document.getParagraphs();

            List<Map<String, Object>> dataList = getData();
            final int size = paragraphs.size();
            for (int i = 0; i < size - 1; i++) {
                final XWPFParagraph xwpfParagraph = paragraphs.get(i);
                final String text = xwpfParagraph.getText();
                if ("${table}".equals(text)) {
                    //第一行为标题头信息
                    String[] titles = {"时间", "国内旅游/人次", "同比增长/减少", "较上年同期"};
                    //第二行开始为数据
                    String[] columnNames = {"year", "peopleCount", "addOrReduce", "previousYear"};
                    WordUtils.createTable(document, xwpfParagraph, dataList, Arrays.asList(titles), Arrays.asList(columnNames));
                }
            }

            String fileName = "导出带表格的word-" + DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
            WordUtils.writeResponse(response, document, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Map<String, Object> getWordData() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", "开发一部");
        map.put("userName", "李四");
        map.put("birtyday", "2015-01-03");
        map.put("address", "陕西省西安市雁塔区xxxxxx");
        map.put("job", "软件工程师");
        return map;
    }

    /**
     * 简单导出没有图片和Excel
     */
    public void simpleWordExport(HttpServletResponse response) {
        try {
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            String templateUrl = "G:\\simpleWord.docx";
            String fileName = "简单word-" + DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
            Map<String, Object> map = getWordData();

            XWPFDocument document = WordExportUtil.exportWord07(templateUrl, map);
            WordUtils.writeResponse(response, document, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Excel导出单个sheet
     * springboot使用easypoi根据模板导出word。解决本地可以导出。打包到服务器导出报错的问题
     * 在本地测试使用IDEA运行都是可以导出的。但是打包以后就报如下错误：
     * cn.afterturn.easypoi.cache.WordCache : java.lang.NullPointerException
     * <p>
     * 具体错误原因是路径不对。打包以后。springboot的路径变为： xxx.jar/BOOT-INF/classes/simpleWord.docx。
     */
    public void exportWord07(HttpServletResponse response) {

        try {
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            //使用文件流方式
            String templateUrl = "G:\\simpleWord.docx";
            InputStream in = new FileInputStream(templateUrl);
//            InputStream in = this.getClass().getResourceAsStream("/word/export.docx");
            String fileName = "简单word-" + DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
            Map<String, Object> map = getWordData();
            WordUtils.exportWord07(response, in, map, fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 导出压缩文件
     */
    public void exportSimpleWord07Zip() {

        try {

            String dateStr = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
            String zipFileName = "G://example.zip";
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            String templateUrl = "G://simpleWord.docx";
            String fileName = "简单word-" + dateStr + ".docx";
            Map<String, Object> map = getWordData();

            WordUtils.exportWord07Zip(templateUrl, map, fileName, zipFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导出压缩文件
     */
    public void exportWord07Zip(HttpServletResponse response) {

        try {

            String dateStr = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
            String zipFileName = "G://导出压缩文件.zip";
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            String templateUrl = "G://simpleWord.docx";
            String fileName = "简单word-" + dateStr + ".docx";
            Map<String, Object> map = getWordData();

            WordUtils.exportWord07Zip(response, templateUrl, map, fileName, zipFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static List<Map<String, Object>> getWordData2() {

        List<Map<String, Object>> resList = new ArrayList<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", "开发一部");
        map.put("userName", "李四");
        map.put("birtyday", "2015-01-03");
        map.put("address", "陕西省西安市雁塔区xxxxxx");
        map.put("job", "软件工程师");
        resList.add(map);

        map = new HashMap<String, Object>();
        map.put("department", "开发二部");
        map.put("userName", "王五");
        map.put("birtyday", "2024-01-03");
        map.put("address", "陕西省西安市雁塔区xxxxxx");
        map.put("job", "软件工程师");
        resList.add(map);

        return resList;
    }


    /**
     * 导出压缩文件
     */
    public void exportMutilWord07Zip2() {

        try {

            String zipFileName = "G://个人简历.zip";
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            String templateUrl = "G://simpleWord.docx";

            Map<String, XWPFDocument> docMap = new HashMap<>();
            List<Map<String, Object>> list = getWordData2();
            for (Map<String, Object> map : list) {
                XWPFDocument doc = WordUtils.exportWord07(templateUrl, map);
                docMap.put(map.get("userName") + "-个人简历.docx", doc);
            }
            WordUtils.exportWord07Zip(docMap, zipFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 导出压缩文件
     */
    public void exportMutilWord07Zip2(HttpServletResponse response) {

        try {
            String zipFileName = "个人简历.zip";
            // 模版文件：starsky-excel/src/main/resource/template/simpleWord.docx
            String templateUrl = "G://simpleWord.docx";

            Map<String, XWPFDocument> docMap = new HashMap<>();
            List<Map<String, Object>> list = getWordData2();
            for (Map<String, Object> map : list) {
                XWPFDocument doc = WordUtils.exportWord07(templateUrl, map);
                docMap.put(map.get("userName") + "-个人简历.docx", doc);
            }
            WordUtils.exportWord07Zip(response,docMap, zipFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}


